package com.gxa.common.interceptor;

import com.gxa.common.uitls.GyUitls;
import com.gxa.common.uitls.JwtUtils;
import com.gxa.entity.User;
import com.gxa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        //如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //执行认证
        if(!JwtUtils.checkToken(token)){
            throw new Exception("token不存在或者无效");
        }

        String username = JwtUtils.getMemberUserNameByJwtToken(token);
        String password = JwtUtils.getMemberPwdByJwtToken(token);

        String passwordSalt = GyUitls.salt(password).toString();

        User user = this.userService.queryByOldPwdAndUname(username, passwordSalt);
        if (user == null){
            throw new Exception("用户不存在，请重新登录");
        }

        return true;
    }
}
